package com.cloud.demo.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.Date;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.cloud.demo.bean.TestSendMsgReq;
import com.cloud.demo.utils.DateUtils;
import com.cloud.demo.utils.Encrypt;
import com.cloud.demo.utils.JacksonUtil;


/**
 * 
 * @ClassName: HttpClient
 * @date 2015-11-11
 *
 */
public class HttpClient {
	private static Log log = LogFactory.getLog(HttpClient.class);
	
	public static String postDataJson(String url, String jsonData,String flag) {
		log.info("【"+flag+" 推送请求地址】" + url);
		log.info("【"+flag+" 推送内容】" + jsonData);
		String result = "";
		CloseableHttpClient client = null;
		String encode = "UTF-8";
		try {
			if (isHttpsUrl(url)) {
				client = registerSSL(getHost(url), "TLS", 8883, "https");
			} else {
				client = HttpClients.createDefault();
			}
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
			HttpPost post = new HttpPost(url);
			post.setConfig(requestConfig);
			// post.removeHeaders("Content-Length");
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-Type", "application/json;charset=" + encode);
			if(StringUtils.isNotBlank(jsonData) ){
			HttpEntity httpEntity = new ByteArrayEntity(jsonData.getBytes("UTF-8"));
			post.setEntity(httpEntity);
			}

			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();

			StringBuffer sb = new StringBuffer();
			InputStreamReader iReader = null;
			InputStream inputStream = entity.getContent();
			iReader = new InputStreamReader(inputStream, encode);
			BufferedReader reader = new BufferedReader(iReader);
			String line = null;

			while ((line = reader.readLine()) != null) {
				sb.append(line + "\r\n");
			}
			iReader.close();
			result = sb.toString();
			log.info("【"+flag+" 推送第三方返回结果】" + result);
		} catch (Exception e) {
			log.error("【"+flag+" 请求错误】" + e.getMessage()+"data:"+jsonData);
			e.printStackTrace();
		} finally {
			if (client != null) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	static CloseableHttpClient registerSSL(String hostname, String protocol, int port, String scheme)
			throws NoSuchAlgorithmException, KeyManagementException {
//		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建SSL上下文实例
		SSLContext ctx = SSLContext.getInstance(protocol);
		// 服务端证书验证
		X509TrustManager tm = new X509TrustManager() {
			public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
					throws java.security.cert.CertificateException {				
			}
			public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
					throws java.security.cert.CertificateException {
				if (chain == null || chain.length == 0)
					throw new IllegalArgumentException("null or zero-length certificate chain");
				if (authType == null || authType.length() == 0)
					throw new IllegalArgumentException("null or zero-length authentication type");

				boolean br = false;
				Principal principal = null;
				for (java.security.cert.X509Certificate x509Certificate : chain) {
					principal = x509Certificate.getSubjectX500Principal();
					log.info("服务器证书信息：" + principal.getName());
					if (principal != null) {
						br = true;
						return;
					}
				}
				if (!br) {
					log.info("服务端证书验证失败！");
				}
			}
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return new java.security.cert.X509Certificate[0];
			}
		};

		// 初始化SSL上下文
		ctx.init(null, new TrustManager[] { tm }, new java.security.SecureRandom());
//		// 创建SSL连接
//		SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//		Scheme sch = new Scheme(scheme, port, socketFactory);
//		// 注册SSL连接
//		httpclient.getConnectionManager().getSchemeRegistry().register(sch);
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

		return HttpClients.custom().setSSLSocketFactory(sslsf).build();
	}
	
	private static boolean isHttpsUrl(String url) {
		return (null != url) && (url.length() > 7) && url.substring(0, 8).equalsIgnoreCase("https://");
	}
	public static String getHost(String url) {
		int index = url.indexOf("//");
		String host = url.substring(index + 2);
		index = host.indexOf("/");
		if (index > 0) {
			host = host.substring(0, index);
		}
		log.debug("host:"+host);
		return host;
	}
	public static void main(String [] args){
		TestSendMsgReq req =new TestSendMsgReq();
		req.setOutId("outId");
//		req.setTel("13391823846");
//		req.setTel("15615312232");
//		req.setTel("15611076994");
		req.setTel("13520007311");
//		req.setTel("18510543438,18679631454");
//		req.setTel("18910715685,13391823846");
//		req.setTel("13366136341,15300296301,13391823846,13520007311");
//		req.setTel("13391823846,15300296301");
//		req.setTel("13520007311,18801181688");
		req.setMsg("浙江台州测试推送请求发送");
//		req.setMsg("刘远,我轰下你手机吧");
//		req.setMsg("邱锶晔的家长您好：中2班周素贤老师发布了通知给您，请点击http://bbtree.com/s/KSGSS0 查看");
//		req.setMsg("【云通讯】七客食品公司使用闪送给您的物品已在途中,单号DH2016031010057164,预计120分钟内到达,请凭收件密码348304完成收件。闪送专员电话石海军18311001321");
//		req.setMsg("测试推送请求地址测试推送请求地址测试推送请求地七客食品公司使用闪送给您的物品已在途中单号首发式打法飞洒风味儿污染物而预计七客食品公司使用闪送给您的物品已在途中单号首发式打法abcDH2016031010057164");
//		req.setMsg("测试推送请求地址测试推送请求地址测试推送请求地址测试推送请求地址测试推送请求地址测试推送请求地址测试推送请求地址abc推送请求地址测试推送请求地址测试推送请求地址123测试推送请求地址测试推送请求地址456测试推送请求地址测试推送请求地址测试推送请求地址测试推送请求地址测试推送请求地址测试推送请求地址测试推送请求地址abc推送请求地址测试推送请求地址测试推送请求地址123测试推送请求地址测试推送请求地址abc结束");
		req.setAppendCode("2055");
		req.setSignature("【测试】");
//		req.setAppendCode("16292");
//		req.setMsg("测试");
//		req.setAppendCode("111");
		String timestamp=DateUtils.formatMdhmsDate(new Date());
		req.setTimestamp(timestamp);
		//'cmpp'+key+secret+timestamp
		String encrypted="cmpp"+"cloopen_Cmpp"+"cmpp_ytx_321"+timestamp;
		req.setEncrypted(Encrypt.encryptMD5(encrypted));
//		req.setSignature("【智慧树】");
		String rs=JacksonUtil.writeValueAsString(req);
//		String rs="{\"msg\":\"【云通讯】测试下发\",\"tel\":\"13391823846\",\"appendCode\":\"1118\",\"timestamp\":\"20160312224939\",\"encrypted\":\"ad0e659f3464112f660e27bc66a1149a\"}";
//		HttpClient.postDataJson("http://120.55.181.172:9000/sgw/cmpp/sendMsg", rs,"cmpp");	
//		HttpClient.postDataJson("http://120.26.224.94:9000/sgw/cmpp/sendMsg", rs,"cmpp");
//		HttpClient.postDataJson("http://120.55.112.241:8080/sgw/cmpp/sendMsg", rs,"cmpp");
//		HttpClient.postDataJson("http://120.55.181.172:9000/sgw/smgp/sendMsg", rs,"smgp");	
//		HttpClient.postDataJson("http://120.55.112.241/sgw/smgpbj/sendMsg", rs,"smgpbj");	
//		HttpClient.postDataJson("http://120.55.112.241:9080/sgw/smgp/sendMsg", rs,"smgphb");
//		HttpClient.postDataJson("http://120.55.112.241:8080/sgw/cmpp/sendMsg", rs,"cmpp");
//		HttpClient.postDataJson("http://127.0.0.1:7080/ccopsgw/sgw/smgp/sendMsg", rs,"smgphb");
//		HttpClient.postDataJson("http://120.26.224.94:9000/sgw/smgpbj/sendMsg", rs,"smgpbj");
//		HttpClient.postDataJson("http://127.0.0.1:7080/ccopsgw/sgw/smgpbj/sendMsg", rs,"smgpbj");	
//		HttpClient.postDataJson("http://120.55.181.172:9080/sgw/smgpbj/sendMsg", rs,"smgpbj");
//		HttpClient.postDataJson("http://127.0.0.1:7080/ccopsgw/sgw/cmpp/sendMsg", rs,"cmppsh");	
//		HttpClient.postDataJson("http://127.0.0.1:7080/ccopsgw/sgw/cmppzj/sendMsg", rs,"cmppzj");
//		HttpClient.postDataJson("http://112.124.118.251:6080/sgw/cmppzj/sendMsg", rs,"cmppzj");
//		HttpClient.postDataJson("http://127.0.0.1:7080/ccopsgw/sgw/sgipqd/sendMsg", rs,"sgipqd");
//		HttpClient.postDataJson("http://112.124.118.251:9080/sgw/sgipqd/sendMsg", rs,"sgipqd");
//		HttpClient.postDataJson("http://112.124.118.251:8080/sgw/smgpbj/sendMsg", rs,"smgpbj");
		HttpClient.postDataJson("http://114.215.237.36:8080/sgw/smgpbj/sendMsg", rs,"smgpbj");
//		String msg="测试xia";
//		System.out.println(msg.length()*2);
//		try {
//			byte[] b= msg.getBytes("GBK");
//			System.out.println(b.length);
//		} catch (UnsupportedEncodingException e) {
//			
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			
//		}
//		int numCount=11;
//		
//		System.out.println((byte)numCount);
//		String tel="8613520007311";
//		if(tel.startsWith("86")){
//			System.out.println(tel.substring(2));
//		}
	}
}
